<?php
namespace app\ucentre\validate;

use think\Validate;

class Register extends Validate
{
    protected $rule =   [
    	'username' => 'require|checkName',
    	'password' => 'require|checkPwd',
    	'repassword' =>'require|confirm:password',
        'email' => 'require|email',
        'agreement' => 'accepted'
    ];
    
    protected $message  =   [
    	'username.require' => '用户名不能为空',
    	'password.require' => '密码不能为空',
    	'repassword.require' => '确认密码不能为空',
    	'repassword.confirm' => '2次密码不一致',
        'email'        => '邮箱格式错误',
        'agreement' => '请勾选同意网站服务条款'
    ];
    
    // 自定义用户名验证规则
    protected function checkName($value, $rule, $data=[])
    {
    	$disableName = configure('register.disableName');
    	$ar = explode(',',$disableName);
    	$nameLengthMin = configure('register.nameLengthMin',4);
    	$nameLengthMax = configure('register.nameLengthMax',15);
    	$msg = "用户名必须是{$nameLengthMin}-{$nameLengthMax}个字符";
		if(mb_strlen($value, 'UTF-8')<$nameLengthMin){
			return $msg;
        }
        if(mb_strlen($value, 'UTF-8')>$nameLengthMax){
        	return $msg;
        }
        if(in_array($value,$ar)){
        	return "该用户名禁止注册";
        }
    	return true;
    }
    
    // 自定义密码验证规则
    protected function checkPwd($value, $rule, $data=[])
    {
    	$strength = configure('register.passwordStrength',[],'array');
    	$pwdLengthMin = configure('register.pwdLengthMin',6);
    	$pwdLengthMax = configure('register.pwdLengthMax',0);

		if(strlen($value)<$pwdLengthMin){
			return "密码长度最少{$pwdLengthMin}位";
        }
        if($pwdLengthMax!=0 && strlen($value)>$pwdLengthMax){
        	return "密码长度最大{$pwdLengthMax}位";
        }
        if(isset($strength['min'])){//小写字母
        	if(!preg_match('/[a-z]+/',$value)){
        		return '密码必须包含小写字母';
        	}
        }
        if(isset($strength['max'])){//大写字母
        	if(!preg_match('/[A-Z]+/',$value)){
        		return '密码必须包含大写字母';
        	}
        }
        if(isset($strength['num'])){//数字
        	if(!preg_match('/[0-9]+/',$value)){
        		return '密码必须包含数字';
        	}
        }
        if(isset($strength['not'])){
        	if($data['username']==$value){
        		return '密码不能和用户名相同';
        	}
        }
        if(isset($strength['bol'])){//符号
        	if(!preg_match('/[!@#$%^&*]+/',$value)){
        		return '密码必须包含数特殊符号';
        	}
        }
        return true;
    }

}
?>